-- 协议名就是文件名
local filename = "genfreeridpool.lua"
--[[
	向freeridpool 中添加新的空余rid段，每次生成10000个，
	根据 maxrid 的值, 如果没有，从10000 开始
]]
local skynet = require "skynet"
local cluster = require "skynet.cluster"
require "skynet.manager"

local filelog = require "filelog"
local redisdao = require "redisdao"
local configdao = require "configdao"

local CMD = {}


function CMD.genfreeridpool( ... )
	local freeridredisconf = configdao.get_cfgsvrs_key("freeridredis")
	local freeridredis =  skynet.newservice("redisdb")
	skynet.call(freeridredis, "lua", "init", freeridredisconf)

	local status, countrid = redisdao.query_data(freeridredis, "SCARD", "freeridpool")

	if tonumber(countrid) > 100000 then
		skynet.kill(freeridredis)
		return true
	end

	local status, maxrid = redisdao.query_data(freeridredis, "GET", "maxrid")

	if(not maxrid) then
		-- 这里应该去获得 freeridpool 以及 mysql 数据库中grid的最大值
		local result = cluster.call("datanode", ".router", "mysqlquery", 1, "select max(rid) as maxrid from rs_info") 
		if( not result[1]) then
			skynet.abort()
		end
		if(result[2][1]["maxrid"]) then
			maxrid = tonumber(result[2][1]["maxrid"])
			if maxrid < 100000 then
				maxrid = 100000
			end
		else
			maxrid = 100000
		end
	else
		maxrid = tonumber(maxrid)
	end

	local newmaxird = maxrid + 900000
	redisdao.query_data(freeridredis, "SET", "maxrid", newmaxird)
	for i = maxrid+1, newmaxird do
		redisdao.query_data(freeridredis, "SADD", "freeridpool", i)
	end
	
	return true
end

return CMD
